package speedball.notice;

import javafx.scene.Node;
import javafx.scene.paint.Color;
import javafx.scene.shape.Shape;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;

public class ModeNoticeService extends SocketService {
    private Shape node;

    public ModeNoticeService(int port, Shape node) {
        super(port);
        this.node = node;
    }

    public Node getNode() {
        return node;
    }

    public void setNode(Shape node) {
        this.node = node;
    }

    @Override
    public void acceptDeal() {
        try {
            System.out.println("开始接受通知指令");
            Thread thread=new Thread(() -> {
                Socket socket = null;
                try {

                    while(true){
                        socket = super.server.accept();

                        //3、获取输入流，并读取客户端信息
                        BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                        //在标准输出上打印从客户端读入的字符串
                        String line = in.readLine();
//            line=br.readLine();
                        //从标准输入读入一字符串
                        //4、获取输出流，响应客户端的请求
                        if (line.equals("start")) {
                            //在系统标准输出上打印读入的字符串

                            System.out.println("Client:" + "游戏启动");
                            node.setFill(Color.BLACK);

                        } else if (line.equals("end")) {

                            System.out.println("Client:" + "游戏退出");
                            node.setFill(Color.rgb(245, 245, 245));
                        } else {
                            System.out.println("Client:未知指令");
                        }
                        //5、关闭资源
                        in.close(); //关闭Socket输入流
                        socket.close(); //关闭Socket
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
            thread.start();
//            Socket socket = null;
//            try {
//                while (true&&) {
//                    System.out.println("dsadsad");
//
////                    invoke(socket);
//                }
//                //2、调用accept()方法开始监听，等待客户端的连接
//                //使用accept()阻塞等待客户请求，有客户
//                //请求到来则产生一个Socket对象，并继续执行
//            } catch (Exception e) {
//                System.out.println("Error." + e);
//                //出错，打印出错信息
//            }
//            super.server.close(); //关闭ServerSocket/
        } catch (Exception e) {//出错，打印出错信息
            e.printStackTrace();
            System.out.println("Error." + e);
        }
    }
}
